package com.chaihu.api.listener.admin.menu;

import com.alibaba.fastjson.JSONObject;
import com.chaihu.api.listener.AbstractServiceApiListener;
import com.chaihu.bean.dto.PageDto;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.in.admin.menu.ListMenusIn;
import com.chaihu.bean.out.admin.menu.ListMenusOut;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.annotation.ChaihuListener;
import com.chaihu.core.context.DataFlowContext;
import com.chaihu.core.event.service.api.ServiceDataFlowEvent;
import com.chaihu.intf.admin.menu.ListMenusService;
import com.chaihu.utils.constant.ServiceCodeMenuConstant;
import com.chaihu.utils.util.BeanConvertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

import java.util.List;


@ChaihuListener("listMenusListener")
public class ListMenusListener extends AbstractServiceApiListener {

    @Autowired
    private ListMenusService listMenusService;

    @Override
    public String getServiceCode() {
        return ServiceCodeMenuConstant.LIST_MENUS;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.GET;
    }


    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }


    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        super.validatePageInfo(reqJson);
    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        PageDto pageDto = BeanConvertUtil.covertBean(reqJson, PageDto.class);

        ListMenusIn queryUserIn = BeanConvertUtil.covertBean(reqJson, ListMenusIn.class);
        queryUserIn.setPageDto(pageDto);
        ResponseResult<List<ListMenusOut>> queryMenusResponseResult = listMenusService.listMenus(queryUserIn);
        if (!StringUtils.equals(MsgCode.SUCCESS.getCode(), queryMenusResponseResult.getCode()) || CollectionUtils.isEmpty(queryMenusResponseResult.getData())) {
            ResponseEntity<String> responseEntity = new ResponseEntity<>(JSONObject.toJSONString(queryMenusResponseResult), HttpStatus.OK);
            context.setResponseEntity(responseEntity);
            return;
        }

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(queryMenusResponseResult), HttpStatus.OK);

        context.setResponseEntity(responseEntity);

    }

}
